// 管理员相关API接口
import axios from 'axios'
import type { AdminStats, AdminDashboardData, AdminActionLog, AdminSettings, SystemNotification } from '../types/admin'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API请求错误:', error)
    return Promise.reject(error)
  }
)

// 获取管理员统计数据
export const getAdminStats = async (): Promise<AdminStats> => {
  return await api.get('/admin/stats')
}

// 获取管理员仪表盘数据
export const getAdminDashboard = async (): Promise<AdminDashboardData> => {
  return await api.get('/admin/dashboard')
}

// 获取操作日志
export const getActionLogs = async (params: {
  page?: number
  pageSize?: number
  actionType?: string
  targetType?: string
  adminId?: number
  startTime?: string
  endTime?: string
}): Promise<{ list: AdminActionLog[], total: number }> => {
  return await api.get('/admin/logs', { params })
}

// 获取系统设置
export const getAdminSettings = async (): Promise<AdminSettings> => {
  return await api.get('/admin/settings')
}

// 更新系统设置
export const updateAdminSettings = async (data: Partial<AdminSettings>): Promise<AdminSettings> => {
  return await api.put('/admin/settings', data)
}

// 获取系统通知
export const getSystemNotifications = async (params: {
  page?: number
  pageSize?: number
  isActive?: boolean
  target?: string
}): Promise<{ list: SystemNotification[], total: number }> => {
  return await api.get('/admin/notifications', { params })
}

// 创建系统通知
export const createSystemNotification = async (data: Omit<SystemNotification, 'id' | 'createdAt'>): Promise<SystemNotification> => {
  return await api.post('/admin/notifications', data)
}

// 更新系统通知
export const updateSystemNotification = async (notificationId: number, data: Partial<SystemNotification>): Promise<SystemNotification> => {
  return await api.put(`/admin/notifications/${notificationId}`, data)
}

// 删除系统通知
export const deleteSystemNotification = async (notificationId: number): Promise<void> => {
  return await api.delete(`/admin/notifications/${notificationId}`)
}

// 清理缓存
export const clearCache = async (): Promise<void> => {
  return await api.post('/admin/clear-cache')
}

// 备份数据库
export const backupDatabase = async (): Promise<{ backupUrl: string }> => {
  return await api.post('/admin/backup-database')
}

// 恢复数据库
export const restoreDatabase = async (file: File): Promise<void> => {
  const formData = new FormData()
  formData.append('file', file)
  return await api.post('/admin/restore-database', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}